<link rel="import" href="../bower_components/app-route/app-route.html">
<link rel="import" href="../bower_components/mist-list/mist-list.html">
<link rel="import" href="../bower_components/paper-fab/paper-fab.html">

<link rel="import" href="schedules/schedule-add.html">
<link rel="import" href="schedules/schedule-page.html">
<link rel="import" href="schedules/schedule-actions.html">
<link rel="import" href="helpers/mist-lists-behavior.html">
<link rel="import" href="helpers/owner-filter-behavior.html">


<dom-module id="page-schedules">
    <template>
        <style include="shared-styles">
            [hidden] {
                display: none !important;
            }
        </style>
        <app-route route="{{route}}" pattern="/:schedule" data="{{data}}"></app-route>
        <template is="dom-if" if="[[_isListActive(route.path)]]" restamp>
            <schedule-actions id="actions" items="[[selectedItems]]" actions="{{actions}}" user="[[model.user.id]]" org="[[model.org]]" members="[[model.membersArray]]">
                <mist-list selectable resizable column-menu multi-sort 
                    apiurl="/api/v1/schedules"
                    id="schedulesList"
                    name="Schedules"
                    primary-field-name="id"
                    frozen=[[_getFrozenColumn()]]
                    visible=[[_getVisibleColumns()]]
                    selected-items="{{selectedItems}}"
                    sort-order=[[sortOrder]]
                    renderers=[[_getRenderers()]]
                    route={{route}}
                    item-map="[[model.schedules]]"
                    actions=[[actions]]
                    user-filter=[[model.sections.schedules.q]]
                    filter-method="[[_ownerFilter()]]"
                    filtered-items-length="{{filteredItemsLength}}">
                    <p slot="no-items-found">No schedules found.</p>
                </mist-list>
            </schedule-actions>

            <div class="absolute-bottom-right" hidden$="[[!check_perm('add','schedule', null, model.org, model.user)]]">
                <paper-fab id="scheduleAdd" icon="add" on-tap="_addResource"></paper-fab>
            </div>
        </template>
        <schedule-add model="[[model]]" section="[[model.sections.schedules]]" hidden$=[[!_isAddPageActive(route.path)]] docs=[[docs]] currency=[[currency]]></schedule-add>
        <schedule-page model="[[model]]" schedule="[[_getSchedule(data.schedule, model.schedules, model.schedules.*)]]" resource-id="[[data.schedule]]" section="[[model.sections.schedules]]" hidden$=[[!_isDetailsPageActive(route.path)]] currency=[[currency]]></schedule-page>
    </template>
    <script>
    Polymer({
        is: 'page-schedules',

        behaviors: [
            mistListsBehavior,
            ownerFilterBehavior,
            rbacBehavior
        ],

        properties: {
            model: {
                type: Object
            },
            actions: {
                type: Array
            },
            selectedItems: {
                type: Array
            },
            currency: {
                type: Object
            }
        },

        _isAddPageActive: function(path) {
            return path == '/+add';
        },

        _isDetailsPageActive: function(path) {
            return path && path != '/+add';
        },

        _isListActive: function(path) {
            return !path;
        },

        _getSchedule: function(id) {
            if (this.model.schedules)
                return this.model.schedules[id];
        },

        _addResource: function(e) {
            this.dispatchEvent(new CustomEvent('go-to', { bubbles: true, composed: true, detail: {
                url: this.model.sections.schedules.add
            } }));

        },

        _getFrozenColumn: function() {
            return ['name'];
        },

        _getVisibleColumns: function() {
            var ret = ['task_type', 'schedule', 'conditions', 'created_by', 'total_run_count', 'tags'];
            if (this.model.org && this.model.org.ownership_enabled == true)
                ret.splice(ret.indexOf('created_by'), 0, 'owned_by');
            return ret;
        },

        _getRenderers: function(schedules) {
            var _this = this;
            return {
                'name': {
                    'body': function(item, row) {
                        return '<strong class="name">' + item + '</strong>';
                    }
                },
                'task_type': {
                    'title': function(item, row) {
                        return 'task';
                    },
                    'body': function(item, row) {
                        if (item.action)
                            return item && item.action.toUpperCase();
                        else if (item.script_id) {
                            var scriptName = _this.model.scripts[item.script_id] ? _this.model.scripts[item.script_id].name : "missing script";
                            return "RUN "+ scriptName;
                        }
                    }
                },
                'tags': {
                    'body': function(item, row) {
                        var tags = item,
                            display = "";
                        for (key in tags) {
                            display += "<span class='tag'>" + key;
                            if (tags[key] != undefined && tags[key] != "")
                                display += "=" + tags[key];
                            display += "</span>";
                        }
                        return display;
                    }
                },
                'owned_by': {
                    'title': function(item, row) {
                        return 'owner';
                    },
                    'body': function(item, row) {
                        return _this.model.members[item] ? _this.model.members[item].name || _this.model.members[item].email || _this.model.members[item].username : '';
                    }
                },
                'created_by': {
                    'title': function(item, row) {
                        return 'created by';
                    },
                    'body': function(item, row) {
                        return _this.model.members[item] ? _this.model.members[item].name || _this.model.members[item].email || _this.model.members[item].username : '';
                    }
                },
                'schedule': {
                    'body': function(item, row) {
                        if (item.startsWith("Interval")) {
                            return item.replace("Interval ", "")
                        } else if (item.startsWith("OneOff")) {
                            var isValid = moment().isValid(item.replace("OneOff date to run ", ""));
                            var time;
                            if (isValid)
                                time = moment.utc(item.replace("OneOff date to run ", "")).fromNow();
                            return time ? time : item;
                        } else if (item.startsWith("Crontab")) {
                            return item.replace("Crontab ", "").replace("(m/h/d/dM/MY)", "");
                        } else
                            return item;
                    }
                },
                'conditions': {
                    'body': function(item, row) {
                        var conditions = item;
                        var display = '';

                        for (var i = 0; i < conditions.length; i++) {
                            var missingLength = 0;
                            if (i == conditions.length - 1 && i > 0)
                                display += "and ";
                            if (conditions[i].type == "machines" && conditions[i].ids.length > 0 && _this.model.machines) {
                                display += "on ";
                                for (var j = 0; j < conditions[i].ids.length; j++) {
                                    if (_this.model.machines[conditions[i].ids[j]]) {
                                        if (j == conditions[i].ids.length - 1 && j > 0 && !missingLength)
                                            display += "and ";
                                        display += _this.model.machines[conditions[i].ids[j]].name;
                                        if (j < conditions[i].ids.length - 2)
                                            display += ",";
                                        display += " ";
                                    } else {
                                        missingLength++;
                                    }
                                }
                                if (missingLength) {
                                    if (missingLength < conditions[i].ids.length)
                                        display += " and "
                                    display += missingLength + " missing machine"
                                    if (missingLength > 1)
                                        display += "s "
                                    else
                                        display += " "
                                }
                            } else if (conditions[i].type == "tags") {
                                display += "on tags ";
                                for (var p in conditions[i].tags) {
                                    display += "<span class='tag'>" + p;
                                    if (conditions[i].tags.p != undefined && conditions[i].tags.p != "")
                                        display += "=" + conditions[i].tags.p;
                                    display += "</span>";
                                }
                            }
                            if (conditions[i].type == "age")
                                display += "older than " + conditions[i].minutes + "min ";
                            else if (conditions[i].type == "field" && conditions[i].field == "cost__monthly")
                                display += "cost more than $" + conditions[i].value + "/month ";
                            else if (conditions[i].type == "field")
                                display += conditions[i].field + " " + conditions[i].value + " ";
                        }

                        return display;
                    }
                }
            }
        }
    });
    </script>
</dom-module>